package com.bw.a2207a.view.fragment

import android.content.Intent
import android.view.View
import android.widget.CheckBox
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.launcher.ARouter
import com.alipay.sdk.app.PayTask
import com.bw.a2207a.R
import com.bw.a2207a.base.BaseFragment
import com.bw.a2207a.bean.CartBean
import com.bw.a2207a.databinding.FragmentCartBinding
import com.bw.a2207a.view.PayResultActivity
import com.bw.a2207a.view.adapter.CartAdapter
import com.bw.a2207a.viewmodel.GoodsDetailViewModel
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


/**
 * create an instance of this fragment.
 */
class CartFragment :
    BaseFragment<FragmentCartBinding, GoodsDetailViewModel>(R.layout.fragment_cart) {
    lateinit var adapter: CartAdapter
    val datas = mutableListOf<CartBean>()

    //总数量
    var count = 0;

    //选中数量
    var countChecked = 0;
    //总价
    var price = 0;

    override fun initData() {
        viewModel.goodsCarsLiveData.observe(this) {
            if (it.code == 200) {
                if (it.data.isNotEmpty()) {
                    datas.clear()
                    datas.addAll(it.data)
                    adapter.notifyDataSetChanged()
                    binding.rvCar.visibility = View.VISIBLE
                    binding.tvEmpty.visibility = View.GONE

                    //设置总数量及总价格
                    datas.forEach() {
                        //count = count+it.count
                        count += it.count//数量相加
//                        price = price+it.goods_default_price*it.count

                    }

                    binding.tvCount.text = "总数量：${count}"
                } else {
                    //显示空页面
                    binding.tvEmpty.visibility = View.VISIBLE
                    binding.rvCar.visibility = View.GONE
                }
            }
        }
    }

    override fun initView() {
        //获取购物车列表
        viewModel.getCar()
        binding.rvCar.layoutManager = LinearLayoutManager(activity)
        adapter = CartAdapter(R.layout.item_cart_layout, datas)
        binding.rvCar.adapter = adapter

        adapter.addChildClickViewIds(R.id.tv_delete, R.id.item_check)
        adapter.setOnItemChildClickListener { adapter, view, position ->
            if (view.id == R.id.tv_delete) {
                //删除
                viewModel.deleteCar(datas.get(position).id)

                datas.removeAt(position)
                adapter.notifyDataSetChanged()

            } else if (view.id == R.id.item_check) {
                //获取checkBox 控件
                val checkBox = view.findViewById<CheckBox>(R.id.item_check)
                //获取checkBox 的选中状态
                datas.get(position).isChecked = checkBox.isChecked

                //计算选中数据的数量及总价
                handleCount()
            }
        }


        //处理全选按钮
        binding.checkAll.setOnClickListener {
            datas.forEach {
                //获取 checkAll的选中状态，赋值给datas中的所以item
                it.isChecked = binding.checkAll.isChecked
            }
//            datas.forEachIndexed { index, cartBean ->
//                cartBean.isChecked = binding.checkAll.isChecked
//            }
            //1重新计算选中的数量及价格

            //计算选中数据的数量及总价
            handleCount()

            //2刷新adapter，改变itemview的 checkBox 样式
            adapter.notifyDataSetChanged()

        }

        //处理立即支付
        binding.tvPay.setOnClickListener {
            val orderInfo: String =
                "app_id=2015052600090779&biz_content=%7B%22timeout_expres" // 订单信息

            val payRunnable = Runnable {
                val alipay = PayTask(activity)
                val result = alipay.payV2(orderInfo, true)
                if (result != null) {
                    //支持成功，跳转页面
                    ARouter.getInstance()
                        .build("/main/PayResultActivity")
                        .withInt("price",price)
                        .navigation()
                    startActivity(Intent(activity, PayResultActivity::class.java))
                }
            }
            // 必须异步调用
            // 必须异步调用
            val payThread = Thread(payRunnable)
            payThread.start()

        }
    }

    /**
     * 处理选中数据
     */
    private fun handleCount() {
        countChecked = 0
        price = 0
        //设置总数量及总价格
        datas.forEach() {
            //变量选中的商品
            if (it.isChecked) {
                countChecked += it.count//数量相加
                price += it.goods_default_price * it.count//单价*数量
            }
        }

        //设置底部控件
        binding.tvPay.text = "结算：${countChecked}"
        binding.tvPrice.text = "${price} 元"

        //更新全选按钮
        //判断datas中的总数量是否等于 选中的数量；如果相等全选；否则是未全选
        if (count == countChecked) {
            binding.checkAll.isChecked = true
        } else {
            binding.checkAll.isChecked = false
        }
    }



    @Subscribe(threadMode = ThreadMode.MAIN)
    fun handleCount(msg:String){
        countChecked = 0
        price = 0
        //设置总数量及总价格
        datas.forEach() {
            //变量选中的商品
            if (it.isChecked) {
                countChecked += it.count//数量相加
                price += it.goods_default_price * it.count//单价*数量
            }
        }

        //设置底部控件
        binding.tvPay.text = "结算：${countChecked}"
        binding.tvPrice.text = "${price} 元"

        //更新全选按钮
        //判断datas中的总数量是否等于 选中的数量；如果相等全选；否则是未全选
        if (count == countChecked) {
            binding.checkAll.isChecked = true
        } else {
            binding.checkAll.isChecked = false
        }
    }

    override fun onStart() {
        super.onStart()
        EventBus.getDefault().register(this)
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

}